package com.dl.dlcommon.aop;


import com.dl.dlcommon.annotation.Login;
import com.dl.dlcommon.exception.LoginException;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.lang.reflect.Method;

/**
 * 校验是否登录
 *
 * @author DL
 * @create 2024-03-20 16:20
 */
@Aspect
@Component
@Slf4j
@Order(1)
public class LoginAspect {

    /**
     * @within 注解表示在类级别上，@annotation 注解表示在方法级别上。
     *
     * @author DL
     * @date 2024/03/20
     */
    @Pointcut("@within(com.dl.dlcommon.annotation.Login) || @annotation(com.dl.dlcommon.annotation.Login)")
    private void pointCut() {
    }

    @Before("pointCut()")
    public void loginAspect(JoinPoint point) throws LoginException {
        Signature signature = point.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        Login login = method.getAnnotation(Login.class);

        if (login == null) {
            // 类级别上的注解
            Class<?> declaringType = method.getDeclaringClass();
            login = declaringType.getAnnotation(Login.class);
        }

        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (servletRequestAttributes == null) {
            throw new RuntimeException("RequestAttributes is null");
        }

        String key = login.key();
        log.info("key:{}", key);

        // token校验逻辑
        HttpServletRequest request = servletRequestAttributes.getRequest();

        if (!"1".equals(request.getParameter("test"))){
            String authorizationHeader = request.getHeader(key);
            if (authorizationHeader == null || authorizationHeader.isEmpty()){
                throw new LoginException("token异常:" + key);
            }
        }
    }
}
